package com.example.administrator.caigou51.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ab.util.AbViewUtil;
import com.alibaba.fastjson.JSON;
import com.example.administrator.caigou51.EventBusClass.GotoFragment;
import com.example.administrator.caigou51.EventBusClass.UpdateShopCarFragment;
import com.example.administrator.caigou51.EventBusClass.UpdateShopCarFragmentRemove;
import com.example.administrator.caigou51.EventBusClass.UpdateShopCarRedCount;
import com.example.administrator.caigou51.R;
import com.example.administrator.caigou51.activity.CheckOrderActivity;
import com.example.administrator.caigou51.activity.GBaseActivity;
import com.example.administrator.caigou51.activity.LoginActivity;
import com.example.administrator.caigou51.activity.MainActivity;
import com.example.administrator.caigou51.bean.MainDataBean;
import com.example.administrator.caigou51.bean.ShopCarBean;
import com.example.administrator.caigou51.global.App;
import com.example.administrator.caigou51.global.Constant;
import com.example.administrator.caigou51.recyclerCard.basic.MaterialListAdapter;
import com.example.administrator.caigou51.recyclerCard.basic.MaterialListView;
import com.example.administrator.caigou51.recyclerCard.card.ShopCarCard;
import com.example.administrator.caigou51.recyclerCard.card.UserCenterCard;
import com.example.administrator.caigou51.request.BaseResponse;
import com.example.administrator.caigou51.request.ICallBackForRequestServer;
import com.example.administrator.caigou51.request.RequestServerManager;
import com.example.administrator.caigou51.util.MyMathUtial;
import com.example.administrator.caigou51.util.ToastUtil;
import com.example.administrator.caigou51.widget.dialog.SweetDialogManager;

import java.util.ArrayList;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;
import de.greenrobot.event.EventBus;


/**
 * Created by Administrator on 2016/5/19/019.
 */
public class ShopCarFragment extends BaseFragment implements View.OnClickListener{
    private View holderView;
    public MaterialListView material_listview;
    RelativeLayout mTopbar;
    private boolean isScaled = false;
    boolean isEditState=false;


    private TextView textViewRightText;
    private ImageView iamgeViewAllCheck;
    private LinearLayout linearLayoutTotal,linearLayoutEmpty;
    private TextView textViewGoodsTotal;
    private TextView textViewGoodsCount;
    private TextView textViewCollect;
    private TextView textViewDel;
    private TextView textViewGoJisSuan,textViewSuiBian;
    private boolean isAllCheck=false;
    public static  int allUpdatecount;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (holderView == null) {
            holderView = inflater.inflate(R.layout.fragment_shopcar, container, false);

            material_listview= (MaterialListView) holderView.findViewById(R.id.material_listview);
            mTopbar = (RelativeLayout) holderView.findViewById(R.id.topbar);

            linearLayoutEmpty = (LinearLayout) holderView.findViewById(R.id.linearLayoutEmpty);linearLayoutEmpty.setOnClickListener(this);
            textViewSuiBian = (TextView) holderView.findViewById(R.id.textViewSuiBian);textViewSuiBian.setOnClickListener(this);
            textViewRightText = (TextView) holderView.findViewById(R.id.textViewRightText);textViewRightText.setOnClickListener(this);
            iamgeViewAllCheck = (ImageView) holderView.findViewById(R.id.iamgeViewAllCheck);iamgeViewAllCheck.setOnClickListener(this);
            linearLayoutTotal = (LinearLayout) holderView.findViewById(R.id.linearLayoutTotal);
            textViewGoodsTotal = (TextView) holderView.findViewById(R.id.textViewGoodsTotal);
            textViewGoodsCount = (TextView) holderView.findViewById(R.id.textViewGoodsCount);
            textViewCollect = (TextView) holderView.findViewById(R.id.textViewCollect);textViewCollect.setOnClickListener(this);
            textViewDel = (TextView) holderView.findViewById(R.id.textViewDel);textViewDel.setOnClickListener(this);
            textViewGoJisSuan = (TextView) holderView.findViewById(R.id.textViewGoJisSuan);textViewGoJisSuan.setOnClickListener(this);
            EventBus.getDefault().register(this);
            initDatas();
           // fillArrayInListView(App.getShopCarList());
            if (App.getUserBean()!=null && App.getUserBean().getIs_verified()==App.PassValue) {
                TaskGetShopCarData(false);
            }
        }
        ViewGroup parent = (ViewGroup) holderView.getParent();
        if (parent != null) {
            parent.removeView(holderView);
        }
        if (!isScaled) {
            AbViewUtil.scaleContentView((ViewGroup) holderView);
            isScaled = true;
        }

        return holderView;
    }



    protected void initDatas() {
        if (App.getShopCarList()!=null && App.getShopCarList().size()>0) {

            linearLayoutEmpty.setVisibility(View.GONE);
            if (!isEditState) {
                textViewRightText.setText("编辑");
                linearLayoutTotal.setVisibility(View.VISIBLE);
                textViewGoJisSuan.setVisibility(View.VISIBLE);
                textViewDel.setVisibility(View.GONE);
                textViewCollect.setVisibility(View.GONE);
            } else {
                textViewRightText.setText("完成");
                linearLayoutTotal.setVisibility(View.GONE);
                textViewGoJisSuan.setVisibility(View.GONE);
                textViewDel.setVisibility(View.VISIBLE);
                textViewCollect.setVisibility(View.VISIBLE);
            }
        }else
        {
            linearLayoutEmpty.setVisibility(View.VISIBLE);
        }


    }


    protected void fillArrayInListView( List<ShopCarBean> list) {

        if (list!=null) {
            for (ShopCarBean shopCarBean : list) {
                ShopCarCard shopCarCard = new ShopCarCard(getActivity());
                shopCarCard.setShopCarBean(shopCarBean);
                material_listview.add(shopCarCard);
            }

            CacalcuteTotal(list);
        }/*else
        {
            ShopCarBean shopCarBean =new ShopCarBean();
            shopCarBean.setShip_price("33.00");
            shopCarBean.setTitle("asdas");
            shopCarBean.setProduct_spec("dsfs");
            shopCarBean.setItemid("sda");
            shopCarBean.setAmount("121");
            shopCarBean.setNumber(44);
            ShopCarCard shopCarCard = new ShopCarCard(getActivity());
            shopCarCard.setShopCarBean(shopCarBean);
            material_listview.add(shopCarCard);


            ShopCarBean shopCarBean2 =new ShopCarBean();
            shopCarBean2.setShip_price("11.00");
            shopCarBean2.setTitle("asd12s");
            shopCarBean2.setProduct_spec("dgfdsfs");
            shopCarBean2.setItemid("dfsda");
            shopCarBean2.setAmount("51");
            shopCarBean2.setNumber(12);
            ShopCarCard shopCarCard2 = new ShopCarCard(getActivity());
            shopCarCard2.setShopCarBean(shopCarBean2);
            material_listview.add(shopCarCard2);

            List<ShopCarBean> slist=new ArrayList<>();
            slist.add(shopCarBean);
            slist.add(shopCarBean2);
            App.saveShopCarList(slist);
            CacalcuteTotal(App.getShopCarList());
        }*/
    }

    private void CacalcuteTotal(List<ShopCarBean> list) {



            float total = 0;
            int totalCount = 0;
            for (ShopCarBean shopCarBean : list) {

                if (shopCarBean.getCheck())
                {

                    total = total + shopCarBean.getNumber() * Float.parseFloat(shopCarBean.getShip_price());
                    totalCount = totalCount + shopCarBean.getNumber();
                }
            }
            textViewGoodsTotal.setText(MyMathUtial.saveTwoXiaoShu(total));
            textViewGoodsCount.setText(totalCount + "件");

        if (total>0)
        {
            textViewGoJisSuan.setBackgroundColor(getActivity().getResources().getColor(R.color.color_ee4528));
        }else
        {
            textViewGoJisSuan.setBackgroundColor(getActivity().getResources().getColor(R.color.color_b8bebe));
        }

    /*   if (bean!=null)
       {
           if (isCheck)
           {
               total=total+bean.getNumber() * Float.parseFloat(bean.getShip_price());
               totalCount = totalCount + bean.getNumber();
               textViewGoodsTotal.setText(total + "");
               textViewGoodsCount.setText(totalCount + "");
           }else
           {
               total=total-bean.getNumber() * Float.parseFloat(bean.getShip_price());
               totalCount = totalCount - bean.getNumber();
               textViewGoodsTotal.setText(total + "");
               textViewGoodsCount.setText(totalCount + "");
           }
       }*/
    }

    public void TaskGetShopCarData(final boolean isloadmore) {
        RequestServerManager.getInstanceDIY().handleMethodDIY((GBaseActivity) getActivity(), null, isloadmore, null,
                Constant.getRootUrl() + Constant.Action.Action_GetCarList, Constant.Action.Action_GetCarList, RequestServerManager.getInstanceDIY().
                        getRequestParams(Constant.Action.Action_GetCarList,App.getUserBean().getUserid(),App.getUserBean().getSession_id()), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        // JSONObject jsonObject = (JSONObject) result.getData();
                         List<ShopCarBean> shopCarBeanList = JSON.parseArray(result.getData().toString(), ShopCarBean.class);
                        App.getShopCarList().clear();
                        App.getShopCarList().addAll(shopCarBeanList);
                        App.saveShopCarList(shopCarBeanList);
                        material_listview.clear();
                        fillArrayInListView(App.getShopCarList());
                      //  material_listview.getAdapter().notifyDataSetChanged();

                        //刷新所有购物车的红点
                        EventBus.getDefault().post(new UpdateShopCarRedCount());
                        EventBus.getDefault().post(new UpdateShopCarFragment());
                        initDatas();
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {

                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    public void onEventMainThread(UpdateShopCarFragmentRemove updateShopCarFragmentRemove) {
        TaskGetShopCarData(false);
    }
    public void onEventMainThread(UpdateShopCarFragment updateShopCarFragment) {
        MaterialListAdapter materialListAdapter= (MaterialListAdapter) material_listview.getAdapter();

        int count=0;

        //刷新是否全选
        for (int i=0;i<materialListAdapter.getAllList().size();i++)
        {
            ShopCarCard shopCarCard= (ShopCarCard) materialListAdapter.getAllList().get(i);

                if (shopCarCard.getShopCarBean().getCheck())
                    count+=1;

        }
        if (count==materialListAdapter.getAllList().size())
        iamgeViewAllCheck.setImageResource(R.drawable.icon_yes_green);
        else
        iamgeViewAllCheck.setImageResource(R.drawable.icon_circle_grey);

      CacalcuteTotal(App.getShopCarList());
        if (App.getShopCarList()!=null && App.getShopCarList().size()>0) {

            linearLayoutEmpty.setVisibility(View.GONE);
         /*   if (!isEditState) {
                textViewRightText.setText("编辑");
                linearLayoutTotal.setVisibility(View.VISIBLE);
                textViewGoJisSuan.setVisibility(View.VISIBLE);
                textViewDel.setVisibility(View.GONE);
                textViewCollect.setVisibility(View.GONE);
            } else {
                textViewRightText.setText("完成");
                linearLayoutTotal.setVisibility(View.GONE);
                textViewGoJisSuan.setVisibility(View.GONE);
                textViewDel.setVisibility(View.VISIBLE);
                textViewCollect.setVisibility(View.VISIBLE);
            }*/
        }else
        {
            linearLayoutEmpty.setVisibility(View.VISIBLE);
        }
      /*  if (material_listview!=null && material_listview.getAdapter().getItemCount()>0 && material_listview.getChildCount()>0) {
            MaterialListAdapter adapter= (MaterialListAdapter) material_listview.getAdapter();
            adapter.getAllList().clear();
            adapter.notifyDataSetChanged();
            fillArrayInListView(App.getShopCarList());
        }*/
     //   material_listview.getAdapter().notifyDataSetChanged();

    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (App.getShopCarList()!=null && App.getShopCarList().size()==0)
        {
            isEditState=false;
        }
        allUpdatecount=0;
        if (isVisibleToUser) {
            if (App.getUserBean()!=null && App.getUserBean().getIs_verified()==App.PassValue) {
                TaskGetShopCarData(false);
            }else
            {
                initDatas();
            }
            //相当于Fragment的onResume
        } else {
            //相当于Fragment的onPause

        }

    }
    private void TaskUpdateCar(ShopCarBean shopCarBean, GBaseActivity gBaseActivity, final int totalCount) {
        RequestServerManager.getInstanceDIY().handleMethodDIY(gBaseActivity, null, false, null,
                Constant.getRootUrl() + Constant.Action.Action_UpdateCarList, Constant.Action.Action_UpdateCarList, RequestServerManager.getInstanceDIY().
                        getRequestParams(Constant.Action.Action_UpdateCarList,App.getUserBean().getUserid(),App.getUserBean().getSession_id(),shopCarBean.getItemid(),shopCarBean.getNumber()+""), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        allUpdatecount=allUpdatecount+1;
                         if (totalCount==allUpdatecount)
                         {
                             Intent intent =new Intent(getActivity(), CheckOrderActivity.class);
                             intent.putExtra(CheckOrderActivity.TagItemIDS,getCheckIDS());
                             intent.putExtra(CheckOrderActivity.TagType,CheckOrderActivity.TagTypeShopCar);
                             getActivity().startActivity(intent);
                             allUpdatecount=0;
                             App.saveShopCarList(App.getShopCarList());

                         }
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {
                        allUpdatecount=0;
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.textViewRightText:

                if (!isEditState)
                {
                    isEditState=true;
                    textViewRightText.setText("完成");
                    linearLayoutTotal.setVisibility(View.GONE);
                    textViewGoJisSuan.setVisibility(View.GONE);
                    textViewDel.setVisibility(View.VISIBLE);
                    textViewCollect.setVisibility(View.VISIBLE);
                }else
                {
                    isEditState=false;
                    textViewRightText.setText("编辑");
                    linearLayoutTotal.setVisibility(View.VISIBLE);
                    textViewGoJisSuan.setVisibility(View.VISIBLE);
                    textViewDel.setVisibility(View.GONE);
                    textViewCollect.setVisibility(View.GONE);
                }
                break;

            case R.id.iamgeViewAllCheck:
                if (isAllCheck) {
                    for (int i = 0; i < App.getShopCarList().size(); i++) {
                        App.getShopCarList().get(i).setCheck(true);
                        material_listview.getAdapter().notifyDataSetChanged();
                    }
                    CacalcuteTotal(App.getShopCarList());
                    isAllCheck=false;
                    iamgeViewAllCheck.setImageResource(R.drawable.icon_yes_green);
                }else
                {
                    for (int i = 0; i < App.getShopCarList().size(); i++) {
                        App.getShopCarList().get(i).setCheck(false);
                        material_listview.getAdapter().notifyDataSetChanged();
                    }
                    CacalcuteTotal(App.getShopCarList());
                    isAllCheck=true;
                    iamgeViewAllCheck.setImageResource(R.drawable.icon_circle_grey);
                }
                break;
            case R.id.textViewSuiBian:
                Intent intent = new Intent(getActivity(),MainActivity.class);
                startActivity(intent);
                EventBus.getDefault().post(new GotoFragment(MainActivity.TAB_ShouYe));
                break;
            case R.id.textViewGoJisSuan:
                if (App.getShopCarList()!=null)
                {
                    //先计算出总价钱
                    MaterialListAdapter materialListAdapter= (MaterialListAdapter) material_listview.getAdapter();
                    for (int i=0;i<materialListAdapter.getAllList().size();i++)
                    {
                        ShopCarCard shopCarCard= (ShopCarCard) materialListAdapter.getAllList().get(i);
                        if (shopCarCard!=null && shopCarCard.getEditText()!=null)
                        shopCarCard.getEditText().clearFocus();
                    }
                    int tc=0;
                    for (int i=0;i<App.getShopCarList().size();i++)
                    {

                        if (App.getShopCarList().get(i).getCheck())
                        {
                          tc+=1;
                        }
                    }
                    for (int i=0;i<App.getShopCarList().size();i++)
                    {
                        ShopCarBean shopCarBean=App.getShopCarList().get(i);
                        if (shopCarBean.getCheck())
                        {
                            if (i==0)
                            TaskUpdateCar(shopCarBean,(GBaseActivity) getActivity(),tc);
                            else
                             TaskUpdateCar(shopCarBean,null,tc);
                        }
                    }
                }

                break;
            case R.id.textViewCollect:
                if (TextUtils.isEmpty( getCheckIDS()))
                {
                    ToastUtil.showToast("请先选择一个商品");
                }else
                    SweetDialogManager.getInstance().showDialogByWarmTitleText((GBaseActivity)getActivity(), "确定将商品移入收藏吗?", "", false, false, new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                        }
                    }, new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            taskMoveCar(false);
                        }
                    });

                break;
            case R.id.textViewDel:
                if (TextUtils.isEmpty( getCheckIDS()))
                {
                    ToastUtil.showToast("请先选择一个商品");
                }else
                    SweetDialogManager.getInstance().showDialogByWarmTitleText((GBaseActivity)getActivity(), "确定要删除选择的商品吗?", "", false, false, new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                        }
                    }, new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            taskDelCar(false);
                        }
                    });

                break;
        }
    }

    private String getCheckIDS() {
        String ids="";
        MaterialListAdapter materialListAdapter= (MaterialListAdapter) material_listview.getAdapter();
        for (int i=0;i<materialListAdapter.getAllList().size();i++)
        {
            ShopCarCard shopCarCard= (ShopCarCard) materialListAdapter.getAllList().get(i);

                if (shopCarCard.getShopCarBean().getCheck())
                    ids+=shopCarCard.getShopCarBean().getItemid()+",";

        }
        if (!TextUtils.isEmpty(ids)) {
            ids = ids.substring(0, ids.length() - 1);
        }
        return ids;
    }
    private void taskMoveCar(final boolean isloadmore) {


        RequestServerManager.getInstanceDIY().handleMethodDIY((GBaseActivity) getActivity(), material_listview, isloadmore, null,
                Constant.getRootUrl() + Constant.Action.Action_MoveCollect, Constant.Action.Action_MoveCollect, RequestServerManager.getInstanceDIY().
                        getRequestParams(Constant.Action.Action_MoveCollect,App.getUserBean().getUserid(),App.getUserBean().getSession_id(),getCheckIDS()), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        // JSONObject jsonObject = (JSONObject) result.getData();
                        ToastUtil.showToast("操作成功");
                        TaskGetShopCarData(false);

                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {

                    }
                });
    }
    private void taskDelCar(final boolean isloadmore) {


        RequestServerManager.getInstanceDIY().handleMethodDIY((GBaseActivity) getActivity(), material_listview, isloadmore, null,
                Constant.getRootUrl() + Constant.Action.Action_DelShopCar, Constant.Action.Action_DelShopCar, RequestServerManager.getInstanceDIY().
                        getRequestParams(Constant.Action.Action_DelShopCar,App.getUserBean().getUserid(),App.getUserBean().getSession_id(),getCheckIDS()), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        // JSONObject jsonObject = (JSONObject) result.getData();
                        ToastUtil.showToast("操作成功");
                       TaskGetShopCarData(false);
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {

                    }
                });
    }

}
